<template lang='pug'>
  .page(@click="dropdownShow = false")
    Form.ivu-row(ref="formData" :model="formData" :label-width="90")
      FormItem.ivu-col.ivu-col-span-24.mb-10(label="主题：" prop="")
        Input(v-model="formData.theme" placeholder="请输入" clearable)
      FormItem.ivu-col.ivu-col-span-24.mb-5(label="收件人：")
        .mail-inbox(@click.stop="inputFocus")
          template(v-for="item in toInboxList")
            Tag(closable @on-close="handleClose(item.id)") {{item.name}}
          //- template(v-for="item in choosedListId")
          //-   Tag(closable @on-close="handleClose_2(item)") {{setName(item)}}
          input.searchinput(ref="searchinput" v-model="serachValue" type="text" @keyup="inputKeyUp" autocomplete="off" spellcheck="false" :style="{width:inputWidth}")
        div.mail-select
          span.mr-5(@click="showModal") 选择
          Icon(type="ios-add-circle")
        .ivu-select-multiple
          .ivu-select-dropdown(v-show="dropdownShow" style="width:100%" @click.stop="dropdownShow = true")
            ul.ivu-select-dropdown-list
              li.ivu-select-item(v-for="(item, index) in searchResult" :key="index" @click="chooserUser(item.id, item.name, item.powerType)" :class="{'ivu-select-item-selected ivu-select-item-focus' : isChecked(item.id)}") {{item.name}}
                span(v-if="item.companyName || item.positionName") （
                span {{item.companyName}}
                span(v-if="item.positionName") ，
                span {{item.positionName}}
                span(v-if="item.companyName || item.positionName") ）
      FormItem.ivu-col.ivu-col-span-24.mb-5(label="")
        Upload(
          :headers="headers"
          :show-upload-list="false"
          :multiple="true"
          :action="uploadBaseUrl + '/MailManage/Upload?categoryName=邮件管理'"
          :on-success="attachmentsBefore"
        )
          .cursor-pointer
            i.font-18.iconfont.icon-fujian
            span 添加附件
        template(v-for="(item, index) in file")
          .my-tag.mr-20
            .my-tag-inner {{item.Name}}
            .img-close.ivu-icon.ivu-icon-ios-close(@click="deleteFile(item.Id)")
      FormItem.ivu-col.ivu-col-span-24(label="正文：")
        editor(ref="editor" :value="formData.content")
      FormItem.ivu-col.ivu-col-span-24()
        .pull-right
          Button(@click="") 取消
          Button.ml-20(v-if="hasAdd" type="primary" @click="sendMail") 发送
    SelectUser(ref="select_user" @on-confrim="selectConfirm")
</template>

<script>
import Cookies from 'js-cookie'
import MailApi from '../service.js'
import Editor from '_c/editor'
import SelectUser from './modal/selectUser.vue'
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'

import config from '@/config'
// import { setTimeout } from 'timers';

import { debounce } from '@/utils/debounce.js'
const baseUrl =
  process.env.NODE_ENV === 'development'
    ? config.baseUrl.dev
    : config.baseUrl.pro

export default {
  name: '',
  props: {},
  data () {
    return {
      headers: {
        'Authorization': 'Bearer ' + Cookies.get('clientToken')
      },
      dropdownShow: false,
      timer: null,
      inputWidth: '30px',
      serachValue: '',
      searchResult: [],
      choosedListId: [],
      uploadBaseUrl: baseUrl,
      formData: {
        theme: '',
        originalId: '',
        name: '',
        fromId: '',
        attaIdList: [],
        content: '',
        toIdList: []
      },
      file: [],
      toInboxList: []
    }
  },

  components: {
    Editor,
    SelectUser
  },

  computed: {
    setName () {
      return val => {
        let arr = val.split(',')
        return arr[1]
      }
    },
    // 是否存在
    isChecked () {
      return id => {
        return this.toInboxList.some(item => {
          return item.id === id
        })
      }
    },
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 新增
    hasAdd () {
      return this.actionArr.indexOf('Add') > -1
    }
  },

  beforeMount () {},

  mounted () {},

  methods: {
    ...mapActions([
      'handleInbox',
      'handleOutbox'
    ]),
    inputFocus () {
      this.$refs.searchinput.focus()
      // if (this.serachValue) {
      //   this.serachUser()
      // }
    },
    inputKeyUp (e) {
      let str = e.target.value
      if (str.length < 1) {
        this.inputWidth = '30px'
      } else {
        this.inputWidth = str.length * 20 + 'px'
      }
      this.searchFn()
    },
    searchFn: debounce(function () {
      this.serachUser()
    }, 800),
    // 搜索收件人
    serachUser () {
      MailApi.GetMailUserList({ name: this.serachValue }).then(res => {
        this.dropdownShow = true
        this.searchResult = res.data.data.map(item => {
          return {
            id: item.id,
            name: item.name,
            powerType: item.powerType,
            companyName: item.companyName,
            positionName: item.positionName
          }
        })
      })
    },
    // 选择
    chooserUser (id, name, powerType) {
      this.$refs.searchinput.blur()
      this.serachValue = ''
      let isHas = this.toInboxList.some(item => {
        return item.id === id
      })
      if (isHas) {
        this.toInboxList.splice(this.toInboxList.findIndex(item => item.id === id), 1)
        this.$refs.select_user.closeInboxUser(id)
      } else {
        this.toInboxList.push({
          id: id,
          name: name,
          powerType: powerType
        })
        this.$refs.select_user.addInboxUser({
          id: id,
          name: name,
          powerType: powerType
        })
      }
    },
    showModal () {
      this.$refs.select_user.showFn()
    },
    attachmentsBefore (response, file, fileList) {
      if (response.Success) {
        this.file.push(response.Data)
        this.formData.attaIdList.push(response.Data.Id)
        // console.log(this.formData.attaIdList)
      } else {
        this.$Message.error(response.Message)
      }
    },
    deleteFile (id) {
      this.file.splice(this.file.findIndex(item => item.Id === id), 1)
      // this.formData.attaIdList.remove(id)
      console.log(this.formData.attaIdList)
      MailApi.DeleteAnnex({
        id: id
      }).then(res => {
      })
    },
    selectConfirm (val) {
      this.toInboxList = val
    },
    handleClose (id) {
      this.toInboxList.splice(
        this.toInboxList.findIndex(item => item.id === id),
        1
      )
      this.$refs.select_user.closeInboxUser(id)
    },
    handleClose_2 (val) {
      this.choosedListId.remove(val)
    },
    sendMail () {
      if (!this.formData.theme) {
        this.$Message.warning('请输入邮件主题')
      } else if (this.toInboxList.length < 1) {
        this.$Message.warning('请选择收件人')
      } else {
        this.$Modal.confirm({
          title: '提示',
          content: '<p>确认发送？</p>',
          onOk: () => {
            this.toInboxList.forEach(item => {
              this.formData.toIdList.push(item.id)
            })
            this.formData.name = this.$store.state.user.userName
            this.formData.fromId = this.$store.state.user.userId
            this.formData.content = this.$refs.editor.editor.txt.html()
            console.log(this.formData)
            MailApi.addMail(this.formData).then(res => {
              if (res.data.success) {
                this.$Message.success(res.data.message)
                this.handleOutbox(true)
                Object.assign(this.$data, this.$options.data())
                this.$refs.select_user.cleanUp()
              } else {
                this.$Message.error({
                  content: res.data.message,
                  duration: 5,
                  closable: true
                })
              }
            })
          },
          onCancel: () => {}
        })
      }
    }
  },

  watch: {}
}
</script>
<style lang='less' scoped>
.ivu-select-item{
  span{
    color: #999;
    font-size: 12px;
  }
}
.searchinput{
  border: none;
  height: 36px;
}
.mail-select {
  position: absolute;
  top: 0;
  right: 18px;
  z-index: 9;
  height: 100%;
  line-height: 1;
  display: flex;
  align-items: center;
  color: #0dc2ff;
  cursor: pointer;
}
.cursor-pointer {
  display: flex;
  align-items: center;
  color: #0bc2ff;
}
.mail-inbox {
  background-color: #fff;
  min-height: 36px;
  border-radius: 8px;
  border-color: rgba(255, 255, 255, 0);
  -webkit-box-shadow: 1px 2px 3px rgba(0, 130, 174, 0.05);
  box-shadow: 1px 2px 3px rgba(0, 130, 174, 0.05);
  padding-left: 15px;
  padding-right: 80px;
}
</style>
